import 'package:flutter/services.dart';
import 'package:ycbl/utils/log_util.dart';
import 'package:ycbl/utils/toast_util.dart';

///苹果内购
class ApplePurchasePlugin {

  /// native 端的名字要和这里一致，才能成功匹配
  final _channel = const MethodChannel('bl_apple_purchase');

  static ApplePurchasePlugin _instance;
  factory ApplePurchasePlugin() => _instance ??= ApplePurchasePlugin._();

  ApplePurchasePlugin._() {
    _channel.setMethodCallHandler(_handleMessages);
  }

  ///  处理 Native 端主动调用的方法；  Future 是返回值
  Future<Null> _handleMessages(MethodCall call) async {
    switch(call.method) {
      
      case 'onPayError': {//购买失败
        ToastUtil.showShortToast(call.arguments ?? '未知错误');
        break;
      }
      
      case 'onFinishLastTransaction': { //结束上次的购买
        LogUtil.d('finish last transaction');
        break;
      }
      
      case 'onCompleteTransaction': { //完成购买，二次（后台）验证
        ToastUtil.showShortToast('支付完成，等待后台校验');
        break;
      }

    }
  }

  /// 进入内购流程
  startPurchase(String productId) async {
    try {
      await _channel.invokeMethod('startPurchase', productId);
    } catch (e) {
      ToastUtil.showShortToast(e.message ?? e.toString());
    }

  }

}